<template>
  <a-spin class="merchantList" tip="加载中..." :spinning="isLoading">
    <!-- 主体部分 -->
    <div class="main-body merchant-body">
      <div class="explain-header">
        <div class="explain-main">
          <p class="explain-title">商家指标说明</p>
          <transition name="mybox">
            <div v-show="explainShow" class="explain-box">
              <div class="explain-item">
                <p><span>商品总量：</span>该商家在售产品＋跟进产品+下架产品的数量之和</p>
                <p><span>跟进商品：</span>该商家已创建未上架的产品数量</p>
                <p><span>下架商品：</span>该商家已下架的产品数量</p>
                <p><span>在售商品：</span>该商家上架的产品数量</p>
              </div>
              <div class="explain-item">
                <p><span>实际销量：</span>该商家销售的套餐数量之和</p>
                <p><span>订单流水：</span>该商家销售的订单对应的支付金额</p>
                <p><span>核销数量：</span>该商家核销的套餐数量之和</p>
                <p><span>核销流水：</span>该商家核销的订单对应的支付金额</p>
                <p><span>核销率：</span>核销数量/实际销量 </p>
              </div>
              <div class="explain-item">
                <p><span>退款数量：</span>该商家退款的套餐数量</p>
                <p><span>退款金额：</span>该商家退款的订单对应的支付金额</p>
                <p><span>退款率：</span>退款数量/实际销量 </p>
              </div>
              <div class="explain-item">
                <p><span>商家款：</span>该商家可结算的商家款总额</p>
                <p><span>已提现：</span>该商家累计已提现且到账的资金</p>
                <p><span>待提现：</span>商家款总额-已提现金额</p>
              </div>
            </div>
          </transition>
          <a-button class="explain-btn" type="link" @click="togglebox">
            {{ explainShow ? '收起详情' : '展开详情' }}
            <a-icon type="up" :style="{ fontSize: '12px', color: '#1D6FE9' }" v-if="explainShow"/>
            <a-icon type="down" :style="{ fontSize: '12px', color: '#1D6FE9' }" v-else/>
          </a-button>
        </div>
      </div>
      <div class="filter-search">
        <div class="search">
          <span class="search-name">商家名称：</span>
          <a-input
              placeholder="请输入"
              class="filter-input"
              v-model="search.businessName"
              @pressEnter="handleSearch"
          />
          <span class="search-name">所属行业：</span>
          <a-select placeholder="请选择" class="filter-input" :options="businessCategoryList" allowClear  v-model="search.businessCategory" @change="handleSearch">
          </a-select>
          <span class="search-name">产品经理：</span>
          <a-input
              placeholder="请输入"
              class="filter-input"
              v-model="search.userName"
              @pressEnter="handleSearch"
          />
          <span class="search-name">分公司：</span>
          <a-input
              placeholder="请输入"
              class="filter-input"
              v-model="search.companyName"
              @pressEnter="handleSearch"
          />
          <span class="search-name">入驻时间：</span>
          <a-range-picker separator="-"  :placeholder="['开始时间', '结束时间']" v-model="enterTime" @change="onSelectDateChange"/>
          <a-button class="search-btn" type="primary" @click="handleSearch">查询</a-button>
          <a-button class="rest-btn" @click="clearSearch">重置</a-button>
        </div>
      </div>
      <a-table
          :dataSource="tableList"
          :columns="tableColumns"
          :pagination="false"
          :scroll="{ x: 500, y: tableHeight }"
          :rowKey="(record, index) => index"
          tableLayout="fixed"
          @change="handleTableChange"
      >
        <template slot="businessName" slot-scope="text, record">
          {{record.enterTime | dateFormat('YYYY-MM-DD')}}
        </template>
        <template slot="businessName" slot-scope="text, record">
          <a-tooltip placement="topLeft">
            <template slot="title">
              <span>{{record.businessName}}</span>
            </template>
            {{record.businessName}}
          </a-tooltip>
        </template>
        <template slot="enterTime" slot-scope="text, record">
          {{record.enterTime | dateFormat('YYYY-MM-DD')}}
        </template>
        <template slot="allProductItemNum" slot-scope="text, record">
          {{record.allProductNum}}（{{record.allProductItemNum}}）
        </template>
        <template slot="followProductItemNum" slot-scope="text, record">
          {{record.followProductNum}}（{{record.followProductItemNum}}）
        </template>
        <template slot="offshopProductItemNum" slot-scope="text, record">
          {{record.offshopProductNum}}（{{record.offshopProductItemNum}}）
        </template>
        <template slot="onsaleProductItemNum" slot-scope="text, record">
          {{record.onsaleProductNum}}（{{record.onsaleProductItemNum}}）
        </template>
        <template slot="allOrderMoney" slot-scope="text, record">
          {{price(record.allOrderMoney)}}
        </template>
        <template slot="allCompleteOrderMoney" slot-scope="text, record">
          {{price(record.allCompleteOrderMoney)}}
        </template>
        <template slot="allRefundOrderMoney" slot-scope="text, record">
          {{price(record.allRefundOrderMoney)}}
        </template>
        <template slot="allBusinessMoney" slot-scope="text, record">
          {{price(record.allBusinessMoney)}}
        </template>
        <template slot="rightBusinessMoney" slot-scope="text, record">
          {{price(record.rightBusinessMoney)}}
        </template>
        <template slot="leftBusinessMoney" slot-scope="text, record">
          {{price(record.leftBusinessMoney)}}
        </template>
        <template slot="completeRate" slot-scope="text, record">
          {{formatDecimal(record.completeRate*100,2)}}%
        </template>
        <template slot="refundRate" slot-scope="text, record">
          {{formatDecimal(record.refundRate*100,2)}}%
        </template>
        <template slot="action" slot-scope="text, record">
          <span class="action" @click="LinkToProductDetail(record.businessId)">查看</span>
        </template>
      </a-table>
    </div>

    <!-- 分页 -->
    <div class="paging-container">
      <a-pagination
          v-model="search.pageNum"
          showQuickJumper
          showLessItems
          :showTotal="(total) => `共 ${total} 条`"
          style="margin: 10px 0;"
          :total="total"
          :pageSize="search.pageSize"
          @change="handleTablePageChange"
      />
    </div>

  </a-spin>
</template>

<script>
import {
  getReleaseDetailAdmin,
  getReleaseDetailArea,
  getReleaseDetailBd,
  getReleaseDetailSub,
  getAllBusinessCategory,
  lastDay,
} from "@/service";
import { dateFormat } from 'nearby-common'
import moment from "moment";
import { mscf } from "@/util";
export default {
  name: 'merchantList',
  data() {
    return {
      isLoading: false,
      total: 0,
      search:{
        businessName:undefined,
        businessCategory:undefined,
        userName:undefined,
        companyName:undefined,
        startDay:undefined,
        endDay:undefined,
        pageNum: 1,
        pageSize: 10,
        day:"",
        orderBy:null,
      },
      enterTime:[null, null],
      tab:1,
      tableList:[],
      businessCategoryList:[],
      explainShow: true
    }
  },
  filters: {
    dateFormat
  },
  computed: {
    // table 配置
    tableColumns() {
      return [
        { title: '商家名称', width: 250, fixed: 'left', dataIndex: 'businessName',ellipsis: true, scopedSlots: { customRender: 'businessName' } },
        { title: '所属行业', width: 150, dataIndex: 'businessCategory' },
        { title: '入驻时间', width: 200, dataIndex: 'enterTime',scopedSlots: { customRender: 'enterTime' } },
        { title: '商品总量(套餐)', width: 200, dataIndex: 'allProductItemNum',sorter: true,scopedSlots: { customRender: "allProductItemNum" }},
        { title: '跟进商品(套餐)', width: 200, dataIndex: 'followProductItemNum',sorter: true,scopedSlots: { customRender: "followProductItemNum" }},
        { title: '下架商品(套餐)', width: 200, dataIndex: 'offshopProductItemNum',sorter: true,scopedSlots: { customRender: "offshopProductItemNum" } },
        { title: '在售商品(套餐)', width: 200, dataIndex: 'onsaleProductItemNum',sorter: true,scopedSlots: { customRender: "onsaleProductItemNum" } },
        { title: '实际销量', width: 200, dataIndex: 'allOrderNum',sorter: true},
        { title: '订单流水', width: 200, dataIndex: 'allOrderMoney',sorter: true,scopedSlots: { customRender: "allOrderMoney" }},
        { title: '核销数量', width: 200, dataIndex: 'allCompleteOrderNum',sorter: true },
        { title: '核销流水', width: 200, dataIndex: 'allCompleteOrderMoney',sorter: true,scopedSlots: { customRender: "allCompleteOrderMoney" } },
        { title: '核销率', width: 200, dataIndex: 'completeRate',sorter: true,scopedSlots: { customRender: "completeRate" } },
        { title: '退款数量', width: 200, dataIndex: 'allRefundOrderNum',sorter: true },
        { title: '退款金额', width: 200, dataIndex: 'allRefundOrderMoney',sorter: true,scopedSlots: { customRender: "allRefundOrderMoney" } },
        { title: '退款率', width: 200, dataIndex: 'refundRate',sorter: true,scopedSlots: { customRender: "refundRate" } },
        { title: '商家款', width: 200, dataIndex: 'allBusinessMoney',sorter: true,scopedSlots: { customRender: "allBusinessMoney" } },
        { title: '已提现', width: 200, dataIndex: 'rightBusinessMoney',sorter: true,scopedSlots: { customRender: "rightBusinessMoney" } },
        { title: '待提现', width: 200, dataIndex: 'leftBusinessMoney',sorter: true,scopedSlots: { customRender: "leftBusinessMoney" } },
        { title: '产品经理', width: 200, dataIndex: 'userName' },
        { title: '所属分公司', width: 200, dataIndex: 'companyName' },
        {
          title: '产品明细',
          key: 'operation',
          fixed: 'right',
          width: 100,
          scopedSlots: { customRender: 'action' },
        },
      ]
    }
  },

  methods: {
    LinkToProductDetail(businessId){
      if (process.env.NODE_ENV == "development") {
        this.$router.push({
          path: "/merchant/productList",
          name: "productList",
          query: { businessId: businessId },
        });
        return;
      }
      mscf.emit("openNewSystem", "*", {
        target: "marketing",
        page: "productList",
        params: {},
        query: {
          businessId: businessId,
          _r: (Math.random() * 100).toFixed(0),
        },
      });
    },
    formatDecimal(num, decimal) {
      if (isNaN(num)) return "0.00";
      num = num.toString()
      let index = num.indexOf('.')
      if (index !== -1) {
        num = num.substring(0, decimal + index + 1)
      } else {
        num = num.substring(0)
      }
      return parseFloat(num).toFixed(decimal)
    },
    price(a) {
      var num = Number(a);
      if (isNaN(num)) return "0.00";
      if (!num) {
        //等于0
        return num + ".00";
      } else {
        //不等于0
        num = Math.round(num * 100) / 10000;
        num = num.toFixed(2);
        num += ""; //转成字符串
        var reg =
            num.indexOf(".") > -1
                ? /(\d{1,3})(?=(?:\d{3})+\.)/g
                : /(\d{1,3})(?=(?:\d{3})+$)/g; //千分符的正则
        return num.replace(reg, "$1,"); //千分位格式化
      }
    },
    clearSearch(){
      this.search = {
        businessName: undefined,
        businessCategory: undefined,
        userName: undefined,
        companyName: undefined,
        startDay: undefined,
        endDay: undefined,
        day:this.search.day,
        pageNum: 1,
        pageSize: 10,
        orderBy:null,
      };
      this.enterTime = [null, null];
      this.getTabTableList();
    },
    handleSearch(){
      this.search.pageNum = 1
      this.getTabTableList()
    },
    handleTablePageChange(num) {
      this.search.pageNum = num
      this.getTabTableList()
    },
    onSelectDateChange(data, dateString) {
      this.search.startDay = dateString[0] ? moment(dateString[0]).format('yyyy-MM-DD 00:00:00') : undefined;
      this.search.endDay = dateString[1] ? moment(dateString[1]).format('yyyy-MM-DD 23:59:59') : undefined;
      this.handleSearch();
    },
    getReleaseDetailAdminList(){
      this.isLoading = true
      getReleaseDetailAdmin(this.search).then(res=>{
        this.tableList = res.list;
        this.total = res.total;
      }).finally(() => {
        this.isLoading = false
      })
    },
    getReleaseDetailAreaList(){
      this.isLoading = true
      getReleaseDetailArea(this.search).then(res=>{
        this.tableList = res.list;
        this.total = res.total;
      }).finally(() => {
        this.isLoading = false
      })
    },
    getReleaseDetailBdList(){
      this.isLoading = true
      getReleaseDetailBd(this.search).then(res=>{
        this.tableList = res.list;
        this.total = res.total;
      }).finally(() => {
        this.isLoading = false
      })
    },
    getReleaseDetailSubList(){
      this.isLoading = true
      getReleaseDetailSub(this.search).then(res=>{
        this.tableList = res.list;
        this.total = res.total;
      }).finally(() => {
        this.isLoading = false
      })
    },
    getTabTableList(){
      this.search.orderBy = "enterTime desc";
      this.tableList = [];
      switch (this.tab){
        case 1:
          this.getReleaseDetailAdminList();
          break;
        case 2:
          this.getReleaseDetailAreaList();
          break;
        case 3:
          this.getReleaseDetailBdList();
          break;
        case 4:
          this.getReleaseDetailSubList();
          break;
      }
    },
    getAllBusinessCategory(){
      getAllBusinessCategory().then(res=>{
        this.businessCategoryList = res;
      })
    },
    handleTableChange(pagination, filters, sorter) {
      this.search.pageNum = 1;
      switch (sorter.field){
        case "allProductItemNum":
          if(sorter.order=="ascend"){
            this.search.orderBy = "all_product_num asc";
          }else if(sorter.order=="descend") {
            this.search.orderBy = "all_product_num desc";
          }else {
            this.search.orderBy = null;
          }
          break;
        case "followProductItemNum":
          if(sorter.order=="ascend"){
            this.search.orderBy = "follow_product_num asc";
          }else if(sorter.order=="descend") {
            this.search.orderBy = "follow_product_num desc";
          }else {
            this.search.orderBy = null;
          }
          break;
        case "offshopProductItemNum":
          if(sorter.order=="ascend"){
            this.search.orderBy = "offshop_product_num asc";
          }else if(sorter.order=="descend")  {
            this.search.orderBy = "offshop_product_num desc";
          }else {
            this.search.orderBy = null;
          }
          break;
        case "onsaleProductItemNum":
          if(sorter.order=="ascend"){
            this.search.orderBy = "onsale_product_num asc";
          }else if(sorter.order=="descend"){
            this.search.orderBy = "onsale_product_num desc";
          }else {
            this.search.orderBy = null;
          }
          break;
        case "allOrderNum":
          if(sorter.order=="ascend"){
            this.search.orderBy = "all_order_num asc";
          }else if(sorter.order=="descend"){
            this.search.orderBy = "all_order_num desc";
          }else {
            this.search.orderBy = null;
          }
          break;
        case "allOrderMoney":
          if(sorter.order=="ascend"){
            this.search.orderBy = "all_order_money asc";
          }else if(sorter.order=="descend"){
            this.search.orderBy = "all_order_money desc";
          }else {
            this.search.orderBy = null;
          }
          break;
        case "allCompleteOrderNum":
          if(sorter.order=="ascend"){
            this.search.orderBy = "all_complete_order_num asc";
          }else if(sorter.order=="descend"){
            this.search.orderBy = "all_complete_order_num desc";
          }else {
            this.search.orderBy = null;
          }
          break;
        case "allCompleteOrderMoney":
          if(sorter.order=="ascend"){
            this.search.orderBy = "all_complete_order_money asc";
          }else if(sorter.order=="descend"){
            this.search.orderBy = "all_complete_order_money desc";
          }else {
            this.search.orderBy = null;
          }
          break;
        case "allRefundOrderNum":
          if(sorter.order=="ascend"){
            this.search.orderBy = "all_refund_order_num asc";
          }else if(sorter.order=="descend"){
            this.search.orderBy = "all_refund_order_num desc";
          }else {
            this.search.orderBy = null;
          }
          break;
        case "allRefundOrderMoney":
          if(sorter.order=="ascend"){
            this.search.orderBy = "all_refund_order_money asc";
          }else if(sorter.order=="descend"){
            this.search.orderBy = "all_refund_order_money desc";
          }else {
            this.search.orderBy = null;
          }
          break;
        case "allBusinessMoney":
          if(sorter.order=="ascend"){
            this.search.orderBy = "all_business_money asc";
          }else if(sorter.order=="descend"){
            this.search.orderBy = "all_business_money desc";
          }else {
            this.search.orderBy = null;
          }
          break;
        case "leftBusinessMoney":
          if(sorter.order=="ascend"){
            this.search.orderBy = "left_business_money asc";
          }else if(sorter.order=="descend"){
            this.search.orderBy = "left_business_money desc";
          }else {
            this.search.orderBy = null;
          }
          break;
        case "refundRate":
          if(sorter.order=="ascend"){
            this.search.orderBy = "all_refund_order_num/all_order_num asc";
          }else if(sorter.order=="descend"){
            this.search.orderBy = "all_refund_order_num/all_order_num desc";
          }else {
            this.search.orderBy = null;
          }
          break;
        case "completeRate":
          if(sorter.order=="ascend"){
            this.search.orderBy = "all_complete_order_num/all_order_num asc";
          }else if(sorter.order=="descend"){
            this.search.orderBy = "all_complete_order_num/all_order_num desc";
          }else {
            this.search.orderBy = null;
          }
          break;
        case "rightBusinessMoney":
          if(sorter.order=="ascend"){
            this.search.orderBy = "all_business_money-left_business_money asc";
          }else if(sorter.order=="descend"){
            this.search.orderBy = "all_business_money-left_business_money desc";
          }else {
            this.search.orderBy = null;
          }
          break;
      }
      this.getTabTableList();
    },
    togglebox(){
      this.explainShow = !this.explainShow;
    },
  },
  async created() {
    this.tab = parseInt(this.$route.query.tab);
    this.getAllBusinessCategory();
    const time = await lastDay();
    this.search.day = time;
    await this.getTabTableList();
  }
}
</script>

<style scoped lang="scss">
.merchantList{
  height: 100%;
  background-color: #ffffff;
}
@media screen and (max-width: 1920px){
  .filter-search{
    .filter-input, .search-btn, .rest-btn{
      margin-top: 20px;
    }
  }
}
.filter-search {
  margin: 10px 0;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  overflow: hidden;
  background: #F5F5F5;
  border-radius: 4px;
  border: 1px solid #F0F0F0;
  padding: 10px 14px;
  .search-name{
    margin-left: 20px;
  }
  .search-name:first-child{
    margin-left: 0;
  }
  .search-btn{
    margin-left: 20px;
  }
  .filter-input {
    width: 180px;
  }
  .filter-select {
    width: 140px;
  }
}
/deep/
.ant-table-thead
> tr
> th
.ant-table-column-sorter
.ant-table-column-sorter-inner-full .on {
  color: #bfbfbf !important;
}
.action{
  color: #0090FF;
  cursor: pointer;
}
</style>
